/////////////////////////////////////////////////
//parseHandlerResponse - Draw Board First Time //
/////////////////////////////////////////////////
function parseOneTimeCurreuntStateOfGame(return_data) {
   
    return_data = return_data.trim();
    
    if(return_data.startsWith(CURRENT_STATE)) {
        // recieved data following player move
        return_data = return_data.replace(CURRENT_STATE,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string
        paint_state(split_array);
    }
    else if(return_data.startsWith(END_GAME_MSG)) { //you loose
        return_data = return_data.replace(END_GAME_MSG,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string
        
        //redairect to post-game
        IsGameEnded = LOSER_STATE;    //loser        
        
        paint_state(split_array);
    }
    else if(return_data.startsWith(FORFIET_STATE)) { //you won
        return_data = return_data.replace(FORFIET_STATE,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string
        
        //redairect to post-game
        IsGameEnded = WINNER_STATE;    //won        
        
        paint_state(split_array);
    }
    else if(return_data.startsWith(RETURN_ERROR)) {
        return_data = return_data.replace(RETURN_ERROR,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string
        paint_state(split_array);
    }
    else {
        alert("An error occured, please try ro reload page");
        
        if ("Undefined offset") {   // check if user refresh page while game ended
            window.location.replace("post_game.php");
        }
        else {
            alert(return_data);        
        }
        //document.location.reload(true);
        //should never happend
    }
}
///////////////////////////////////////////////////////////
//parseHandlerResponse - parse response after our turn   //
///////////////////////////////////////////////////////////
function parseHandlerResponse(return_data) {
    ISMYTURN = false;
    return_data = return_data.trim();
    if(return_data.startsWith(CURRENT_STATE)) {
        // recieved data following player move
        return_data = return_data.replace(CURRENT_STATE,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string
        
        //animate my own command
        //in case a refrsh is made, no need for animation 
        if( ! IsBoardPainted) {
            // update to the new board
            paint_state(split_array);
            // Start Waiting for response
            myVar=setTimeout(function(){postGameState(); },ticker);
        }        
        else {
            // Show Anim (after clock is down)
            animate_my_own_command(split_array);       
            // animate will call paint_state! after animation timer ends
            //will start the wait ticker.
        }
  
    }
    else if(return_data.startsWith(END_GAME_MSG)) { 
        // you won
        return_data = return_data.replace(END_GAME_MSG,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string
        
        //redairect to post-game
        IsGameEnded = WINNER_STATE;    
        
        animate_my_own_command(split_array);
    }
    else if(return_data.startsWith(FORFIET_STATE)) { //you loose
        return_data = return_data.replace(FORFIET_STATE,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string
        
        //redairect to post-game
        IsGameEnded = LOSER_STATE;   
        
        paint_state(split_array);
    }
    else if(return_data.startsWith(RETURN_ERROR)) {
        return_data = return_data.replace(RETURN_ERROR,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string
        paint_state(split_array);
        ShowGameMessage("Command Error");
        ISMYTURN = true;
        SetBoardEnable(ISMYTURN);
        postGameState();
    }
    else {
        alert("An error occured, please try ro reload page");
        if ("Undefined offset") {   // check if user refresh page while game ended
            window.location.replace("post_game.php");
        }
        else {
            alert(return_data);        
        }   
        //document.location.reload(true);
        //should never happend
    }
}
/////////////////////////////////////////////////////////////////
// parseStateResponse - parsing response of the waiting timer  //
/////////////////////////////////////////////////////////////////
function parseStateResponse(return_data) {
    ISMYTURN = false;
    SetBoardEnable(ISMYTURN);
    return_data = return_data.trim();
    // check response
    if(return_data.startsWith(CURRENT_STATE)) {
        // recieved normal state from DB
        // check if its my turn
        return_data = return_data.replace(CURRENT_STATE,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string
        //check if player turn or not
        if(split_array[0] == 1) { 
            ////player turn - play   
            
            // Show "Your TURN"
            //SetBoardEnable(true);
            ISMYTURN = true;            

            //in case a refrsh is made, no need for animation 
            if( ! IsBoardPainted) {
                // update to the new board
                paint_state(split_array);  
            }        
            else {
                // Show Anim (after clock is down)
                animate_last_command(split_array);       
                // animate will call paint_state! after timer ends
            }
        }
        else { 
            //op. turn - Continue to wait..
            myVar=setTimeout(function(){postGameState(); },ticker);
        }
    }
    else if(return_data.startsWith(END_GAME_MSG)) { //you loose
        return_data = return_data.replace(END_GAME_MSG,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string
             
        //redairect to post-game
        IsGameEnded = LOSER_STATE;                
             
        if( ! IsBoardPainted) {
            paint_state(split_array);  
        }        
        else {
            animate_last_command(split_array);       
        }
    }
    else if(return_data.startsWith(FORFIET_STATE)) { //you won
        return_data = return_data.replace(FORFIET_STATE,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string

        //redairect to post-game
        IsGameEnded = WINNER_STATE;   
        
        paint_state(split_array);
    }
    else if(return_data.startsWith(RETURN_ERROR)) {
        ShowGameMessage("Server Error");
        return_data = return_data.replace(RETURN_ERROR,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string
        paint_state(split_array);
        myVar=setTimeout(function(){postGameState(); },ticker);
    }
    else {
        alert("An error occured, please try ro reload page");
        if ("Undefined offset") {   // check if user refresh page while game ended
            window.location.replace("post_game.php");
        }
        else {
            alert(return_data);        
        }       
        //document.location.reload(true);
        //should never happend
    }
}

//////////////////////////////////////////////
//parseSurrender - Player click on serender //
//////////////////////////////////////////////
function parseSurrender(return_data) {
    ISMYTURN = false;
    SetBoardEnable(ISMYTURN);
    return_data = return_data.trim();
    if(return_data.startsWith(FORFIET_STATE)) {
        return_data = return_data.replace(FORFIET_STATE,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string        

        //redairect to post-game
        IsGameEnded = LOSER_STATE;    //loser        
        
        paint_state(split_array);
        
    }
    else if(return_data.startsWith(END_GAME_MSG)) {
        return_data = return_data.replace(END_GAME_MSG,""); // remove 'STATE:'
        var split_array = return_data.split(",");   // parse string
        //redairect to post-game
        IsGameEnded = WINNER_STATE;    //Winnwe        
        
        paint_state(split_array);
        
    }
    else {
        document.getElementById("btnForfeit").disabled = false;      //enable Surrender BTN
        alert("An error occured, please try ro reload page");
        alert(return_data);
        //document.location.reload(true);
        //should never happend
    }
}
//////////////////////////////////////////////
//        Enable\Disable Game Board         //
//////////////////////////////////////////////
function SetBoardEnable(bool) {
    
    var ext = "";
    if ( ! bool ) {
        ext = "_dis";
    }
    
    if ( bool ) {
        document.getElementById("divTopMSG").innerHTML = "YOUR TURN";
        document.getElementById("btnSubmit").disabled = false;
        document.getElementById("btnDrawCard").disabled = false;
        PlaceSoldierType.Card = false;
        PlaceSoldierType.i = -1;
        PlaceSoldierType.j = -1;
        AttackType.i = -1;
        AttackType.j = -1;
        ClickHere_CardID = null;
        ClickHere_LastElement = null;  
        NextCommand.Init();
    }
    else {
        document.getElementById("divTopMSG").innerHTML = "<img src='images/game/waiting.gif'/>";
        document.getElementById("btnSubmit").disabled = true;
        document.getElementById("btnDrawCard").disabled = true;        
    }
    
    //Enable - Special Things (images)
    document.getElementById("btnDrawCard").src = "images/game/btn/draw" + ext + ".jpg";
    document.getElementById("btnRestart").src = "images/game/btn/restart" + ext + ".jpg";
    document.getElementById("btnSubmit").src = "images/game/btn/go" + ext + ".jpg";
    
    // enable >> diable = flase !
    bool = !bool;
    
    //Enable\Disable game board - its user turns
    document.getElementById("btnDrawCard").disabled = bool;
    document.getElementById("btnRestart").disabled = bool;
    document.getElementById("btnSubmit").disabled = bool;
    document.getElementById("txtCommand").disabled = bool;    
    document.getElementById("btnSendCommand").disabled = bool;  

}
//////////////////////////////////////////////
//               updateChat                 //
//////////////////////////////////////////////
function updateChat(return_data) {
    return_data = return_data.trim();
    
    if( (return_data.length > 0 ) && (!return_data.startsWith("<br />")) ) {
        var tmpText = document.getElementById("ChatOutput").value;
        document.getElementById("ChatOutput").value = tmpText + "\n" + return_data;
        var textarea = document.getElementById('ChatOutput');
        textarea.scrollTop = textarea.scrollHeight;
    }
}
//////////////////////////////////////////////
//               updateMyChat                 //
//////////////////////////////////////////////
function updateMyChat(return_data) {
    var tmpText = document.getElementById("ChatOutput").value;
    document.getElementById("ChatOutput").value = tmpText + "\n" + return_data;
    var textarea = document.getElementById('ChatOutput');
    textarea.scrollTop = textarea.scrollHeight;    
}

//////////////////////////////////////////////
//           Restart Board Button           //
//////////////////////////////////////////////
function RestartClicked() {
    paint_state(LastParsedState);// paint last state before changes
    SetBoardEnable(ISMYTURN);   // init board
    NextCommand.Init();         // init command
    document.getElementById("txtCommand").value = "";
}

//////////////////////////////////////////////
//             draw_card Button             //
//////////////////////////////////////////////
function DrawCardClicked() {
    
    if ( (Cards[4]["IsEmpty"]) && (!NextCommand.DrawCard) ) {
        // set draw
        Cards[4]["Element"].innerHTML = "<img src='images/game/cards/empty.png' alt='empty card'>";
        NextCommand.DrawCard = true;
        document.getElementById("btnDrawCard").src = "images/game/btn/draw_dis.jpg";
    }
    else {
        if (NextCommand.DrawCard) {
            //unset draw
            Cards[4]["Element"].innerHTML = "";
            NextCommand.DrawCard = false;
            document.getElementById("btnDrawCard").src = "images/game/btn/draw.jpg";  
        }
    }
}

////////////////////////////////////////
//   Soldier Clicked - Attack         //
////////////////////////////////////////
function SoldierClicked(i,j,id) {
    
    //check if op. soldier clicked OR its not my turn OR animation is on
    if ( (id == 2) || (!ISMYTURN) || (ArrayStartIndex>-1)  ) {  
        return false;
    }
    
    //Place\Unplace Attck
    if ( (!PlayerBoard[i][j]["isEmpty"]) && (!NextCommand.Attack) ) {
        // show Attack BG
        PlayerBoard[i][j]["Element"].style.backgroundColor = ATTACK_COLOR;
        NextCommand.Attack = true;
        AttackType.i = i;
        AttackType.j = j;
    }
    else {
        if ( (!PlayerBoard[i][j]["isEmpty"]) && (AttackType.i == i) && (AttackType.j == j) ) {
            PlayerBoard[i][j]["Element"].style.backgroundColor = "transparent";
            NextCommand.Attack = false;
        }
    }
    
}
///////////////////////////////////////////////////
//  UnplaceSoldier after drag and drop in board  //
///////////////////////////////////////////////////
function UnplaceSoldier() {
    
    var i = PlaceSoldierType.i;
    var j = PlaceSoldierType.j;
    
    // remove from board
    PlayerBoard[i][j]["LifeElement"].innerHTML = "";
    PlayerBoard[i][j]["ImageSpanElement"].innerHTML ="";
    //restore card in deck
    Cards[LastCardID]["Element"].innerHTML = LastCardElement;
    
    NextCommand.PlaceSoldier = false;
}



///////////////////////////////////////////////////
//              Click Here ClickThere            //
///////////////////////////////////////////////////
// Cancel Card Selection, after user clicked on card and click again to unselect
function CancelCardSelection(index) {
    //restore old card
    Cards[index]["Element"].innerHTML  = ClickHere_LastElement;
    // nothing is selected
    ClickHere_CardID = null;
}
// Click "HERE"
function CardClick(index) {
    
    // if not my turn OR already place another soldier  OR animation on
    if ( (!ISMYTURN) || (NextCommand.PlaceSoldier) || (ArrayStartIndex>-1) ) {
        return false;
    }
    // if other card clicked before me
    if (ClickHere_CardID != null) {
        //restore other card
        Cards[ClickHere_CardID]["Element"].innerHTML  = ClickHere_LastElement;
    }
    // save elmnt
    ClickHere_LastElement = Cards[index]["Element"].innerHTML;
    Cards[index]["Element"].innerHTML = "<img src='images/game/cards/place.jpg' onclick='CancelCardSelection(" + index + ");' />";

    ClickHere_CardID = index;
}
//Click "THERE"
function CellClick(i , j) {


    // if not my turn OR 
    //    already place another soldier OR 
    //    No Card Selected(clicked) before OR
    //    Animation on
    if ( (!ISMYTURN) || (NextCommand.PlaceSoldier) || (ClickHere_CardID == null) || (ArrayStartIndex>-1) ) {
        return false;
    }

    // check if cell empty (if not there is already soldier)
    if (PlayerBoard[i][j]["IsEmpty"]) {
        
        // ### Show Animation of dragging ###
        
       
        // get boundries of ceel(move the card tothisboundries
        var TargetRect = document.getElementById("p1_board_"+i+j).getBoundingClientRect();
        // boundries of the card we wantto drag (in deck)
        var SourceRect = Cards[ClickHere_CardID]["Element"].getBoundingClientRect();        
        
        // get the draged_card_popup element, and init it
        var DragedCardElement=  document.getElementById("draged_card_popup");
        
        DragedCardElement.innerHTML = ClickHere_LastElement; //Clone Card to view image
        
        // Set position of DragedCardElement popup
        DragedCardElement.style.top = parseInt(SourceRect.top) + "px";
        DragedCardElement.style.left = parseInt(SourceRect.left) + "px";
        // Set popup to visible
        DragedCardElement.style.visibility = "Visible";        


        ShowCardDragAnimation( DragedCardElement,TargetRect.left, TargetRect.top ) ;


        
        // ### PLACE SOLDIER ###
        NextCommand.PlaceSoldier = true;
        PlaceSoldierType.Card = parseInt(ClickHere_CardID);
        PlaceSoldierType.i = i;
        PlaceSoldierType.j = j;
        LastCardElement =  ClickHere_LastElement;
        LastCardID = parseInt(ClickHere_CardID);
        var cType = parseInt(Cards[ClickHere_CardID]["Card_id"]);    //get card num by int
        PlayerBoard[i][j]["LifeElement"].innerHTML = CardsDefs[cType]["HP"];
        PlayerBoard[i][j]["ImageSpanElement"].innerHTML ="<img src='images/game/soldiers/00" + cType + "/1.png' onclick='UnplaceSoldier();'>" ;
        Cards[ClickHere_CardID]["Element"].innerHTML = "";   
        
        //init ClickHereClickThere:
        ClickHere_CardID = null;
        ClickHere_LastElement = null;
    }
}


//////////////////////////////////////////////
//     Submit Command Clicked               //
//////////////////////////////////////////////
function SubmitClicked() {

    var command = document.getElementById("txtCommand").value;
    
    if( command != false ) {
        postGameHandler(command);
    }
}
/////////////////////////////////////////////////
//Go!  Clicked (btn image to submit GUI commnds//
/////////////////////////////////////////////////
function GoClicked() {

    // check Command and send it
    var cmd = NextCommand.GenerateCommandString();
    if ( cmd ) {
        postGameHandler(cmd)
    }
    else {
        ShowGameMessage(NextCommand.ErrorMessage);
    }

}

//////////////////////////////////////////////
//             surrender flow               //
//////////////////////////////////////////////
function SurrenderClicked() {
    
    // on animation - exit
    if ( ArrayStartIndex > -1) {
        return false;
    }
    
    document.getElementById("btnForfeit").disabled = true;      //disable Surrender BTN
    //popup massge "do you really?"
    postGameSurrender();
}

//////////////////////////////////////////////
//               ChatClick                  //
//////////////////////////////////////////////
function ChatClick() {
    
    var chatStr = document.getElementById("ChatInput").value;
    if(chatStr != "") {
        postChatLine(chatStr);
    }
    document.getElementById("ChatInput").value = "";
}
